package dns

import "sync"

/**
 * @brief: 	获取DNS缓存接口
 * @author: haitao.lin
 */
func GetDNSCacheInterface() DNSCacher {
	once.Do(func() {
		gDNSCache = &dnsCache{hostNameMap: make(map[string]string)}
	})
	return gDNSCache
}

/**
 * @brief: 	DNS映射接口
 * @author: haitao.lin
 */
type DNSCacher interface {
	/**
	 * @brief:	更新DNS映射，如果不存在，则添加
	 * @param:	hostname 	主机名
	 * @parma:	host		主机地址
	 * @author: haitao.lin
	 */
	UpdateDNSMapping(hostname string, host string)

	/**
	 * @brief: 	获取主机地址，如果不存在，则返回传入的hostname
	 * @author: haitao.lin
	 */
	GetHost(hostname string) string
}

var once sync.Once
var gDNSCache *dnsCache

type dnsCache struct {
	hostNameMap map[string]string
}

func (dnsCache *dnsCache) UpdateDNSMapping(hostname string, host string) {
	dnsCache.hostNameMap[hostname] = host
}

func (dnsCache *dnsCache) GetHost(hostname string) string {
	host, isOk := dnsCache.hostNameMap[hostname]
	if isOk {
		return host
	}
	return hostname
}
